﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XGetoptCS;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace zgettext
{
    class ProgramOpt
    {
        public string PoFileName { get; set; }

        public string[] SourceFileNames { get; set; }

        public string Keyword { get; set; }
    }

    class Program
    {
        private static void Usage()
        {
            Console.WriteLine("zgettext -k <keyword> -o <out.po> -i <input.cs>");
            Console.WriteLine("\n参数说明：");
            Console.WriteLine("\t-k\tC#代码里翻译字符串的函数名！");
            Console.WriteLine("\t-o\t生成的po文件");
            Console.WriteLine("\t-i\tC#源文件");
            Console.WriteLine("\t-f\tC#源文件列表");
            Console.WriteLine("\t-h\t打印本帮助");
        }

        private static Dictionary<string, bool> _stringBeingTranslated = new Dictionary<string, bool>();

        static void Main(string[] args)
        {
            var opt = ParseOption(args);
            if (opt == null)
                return;

            var regex = new Regex(string.Format("{0}\\(\"([^\"]+)\"\\)", opt.Keyword));
            using (var powriter = new StreamWriter(opt.PoFileName, true, Encoding.UTF8))
            {
                foreach (var source in opt.SourceFileNames)
                {
                    try
                    {
                        using (var reader = new StreamReader(source))
                        {
                            WriteTranslatableStrings(reader, powriter, regex, source);
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(string.Format("处理文件{0}时出错：{1}", source, ex.ToString()));
                    }
                }
            }
        }

        private static void WriteTranslatableStrings(
            StreamReader reader, StreamWriter powriter, Regex regex, string sourceName)
        {
            string line = null;
            int idx = 1;
            while ( (line = reader.ReadLine()) != null )
            {
                var match = regex.Match(line);
                if (match.Success)
                {
                    var value = match.Groups[1].Value;
                    if (!_stringBeingTranslated.ContainsKey(value))
                    {
                        powriter.WriteLine(string.Format("#: {0}:{1}", sourceName, idx));
                        powriter.WriteLine(string.Format("msgid \"{0}\"", match.Groups[1].Value));
                        powriter.WriteLine("msgstr \"\"");
                        powriter.WriteLine();
                        _stringBeingTranslated.Add(value, true);
                    }
                }

                idx++;
            }
        }

        private static ProgramOpt ParseOption(string[] args)
        {
            var parser = new XGetopt();
            char c = '\0';
            var opt = new ProgramOpt();
            while ((c = parser.Getopt(args.Length, args, "hk:o:i:f:")) != '\0')
            {
                switch (c)
                {
                    case 'k':
                        opt.Keyword = parser.Optarg;
                        break;

                    case 'o':
                        opt.PoFileName = parser.Optarg;
                        break;

                    case 'i':
                        opt.SourceFileNames = new string[] { Path.GetFullPath(parser.Optarg) };
                        break;

                    case 'f':
                        opt.SourceFileNames = File.ReadAllLines(Path.GetFullPath(parser.Optarg));
                        break;

                    case 'h':
                    default:
                        Usage();
                        return null;
                }
            }

            return opt;
        }
    }
}
